import React, { PureComponent, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import Moment from 'moment';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  Dropdown,
  Row,
  Col,
  Modal,
  Collapse,
  List,
  message,
  Radio,
  Popconfirm,
  Upload,
  Tooltip,
  InputNumber,
} from 'antd';

import ImageUploader from '../Attachment/ImageUploader';
import AttachmenTable from '../Attachment/AttachmentTable';
import { solo } from '../../../common/solo';
import styles from './LoanEditor.less';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;
const monthFormat = 'YYYY-MM-DD';

const formItemLayout = {
  labelCol: {
    span: 24,
  },
  wrapperCol: {
    span: 24,
  },
};

const formItemLayoutOfHorizon = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 10,
  },
};

const EditableCell = ({ editable, value, onChange }) => (
  <div>
    {editable ? (
      <div>
        <Input
          style={{ margin: '-5px 0' }}
          value={value}
          onChange={e => onChange(e.target.value)}
        />
        {/* <Select style={{ width: 120 }} >
          <Option value={1}>上牌服务费</Option>
          <Option value={2}>GPS安装费</Option>
          <Option value={3} >保险服务费</Option>
          <Option value={4}>其他</Option>
        </Select> */}
      </div>
    ) : (
      value
    )}
  </div>
);

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
@Form.create()
export default class LoanEditor extends PureComponent {
  state = {
    applyOtherCost: [],
    id: '',
    projectId: '',
    intrestList: [],
    subjects: '',
    agreementFileList: [],
    applyDisabled: null,
    attachmentMap: {
      attachs: [],
    },
    assetPrices: null, //资产价格
    firstPayment: null, //首付款
    firstPaymentProportion: null, //首付款比例
    loanAmount: null, //贷款金额
    poundageProportion: null, //手续费率
    poundage: null, //手续费
    loanPeriod: null, //贷款周期
    eachMonth: null, //月供
    addLoanAmt: null, //附加消费分期金额
    applyAmt: null, //申请金额
    feeInputFlag: false, //判断手续费是算还是显示服务器的值
  };

  componentDidMount() {
    const { apply: { applyListDetails } } = this.props;
    const { business } = applyListDetails;
    let attachmentMap = this.state.attachmentMap;
    if (business.attachs.length > 0) {
      for (let i = 0; i < business.attachs.length; i++) {
        attachmentMap.attachs.push({
          uid: business.attachs[i],
          key: business.attachs[i],
          name: business.attachs[i],
          status: 'done',
          url: solo.fileDownload + business.attachs[i],
        });
      }
    }
    this.setState({
      id: this.props.id,
      projectId: this.props.projectId,
      intrestList: business.intrestList,
      applyOtherCost: business.otherCost,
      applyDisabled: this.props.applyDisabled,
      attachmentMap,
      assetPrices: business.dealerPrice ? business.dealerPrice : 0, //资产价格
      firstPayment: business.firstPayment ? business.firstPayment : 0, //首付款
      loanAmount: business.applyAmt ? business.applyAmt : 0, //贷款金额
      poundageProportion: business.intrest ? business.intrest : 0, //手续费率
      loanPeriod: business.loanDuration, //贷款周期
      poundage: business.fee ? business.fee : 0, //手续费
      addLoanAmt: business.addLoanAmt ? business.addLoanAmt : 0, //附加消费分期金额
      applyAmt: business.applyAmt ? business.applyAmt : 0, //申请金额
    });
  }

  appendFeeData = [
    { key: '1', feeField: '上牌服务费', feeValue: 4 },
    { key: '2', feeField: 'GPS安装费', feeValue: 1000, isEditing: true },
  ];

  // constructor(props) {
  //   super(props);

  appendFeeColumns = [
    {
      title: '科目',
      dataIndex: 'costName',
      key: 'costName',
      width: '33%',
      render: (text, record) => this.renderColumnsRetail(text, record, 'costName'),
    },
    {
      title: '费用',
      dataIndex: 'cost',
      key: 'cost',
      width: '33%',
      render: (text, record) => this.renderColumnsRetail(text, record, 'cost'),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        const { editable } = record;
        const { valid } = record;
        return (
          <div className="editable-row-operations">
            {/* {valid == 2 ? */}
            {editable ? (
              <span>
                <a onClick={() => this.saveRetail(record.id)}>保存</a>
                <Popconfirm title="确定要取消吗?" onConfirm={() => this.cancelRetail(record.id)}>
                  <a style={{ marginLeft: 10 }}>取消</a>
                </Popconfirm>
              </span>
            ) : (
              // this.renderDelete(record)
              <div>
                {!this.state.applyDisabled ? (
                  <div>
                    <a onClick={() => this.editRetail(record.id)}>修改</a>
                    <Popconfirm
                      title="确定要删除吗?"
                      onConfirm={() => this.deleteOtherCost(record.id)}
                    >
                      <a style={{ marginLeft: 10 }}>删除</a>
                    </Popconfirm>
                  </div>
                ) : null}
              </div>
            )}
          </div>
        );
      },
    },
  ];
  // this.cacheDataChannel = this.state.applyOtherCost.map(item => ({ ...item }))
  // }

  deleteOtherCost(key) {
    const newData = [...this.state.applyOtherCost];
    this.setState({ applyOtherCost: newData.filter(item => item.id !== key) });
  }

  renderColumnsRetail(text, record, column) {
    return column == 'costName' ? (
      <Select
        onChange={value => this.handleSubjectsSelect(value, record.id, column)}
        disabled={!record.isPreset ? true : !record.isPreset}
        value={record.costName}
      >
        <Option value={'1'}>上牌服务费</Option>
        <Option value={'2'}>GPS安装费</Option>
        <Option value={'3'}>保险服务费</Option>
        <Option value={'4'}>其他</Option>
      </Select>
    ) : (
      <EditableCell
        editable={record.editable}
        value={text}
        onChange={value => this.handleChangeRetail(value, record.id, column)}
      />
    );
  }

  handleSubjectsSelect = (value, key, column) => {
    const newData = [...this.state.applyOtherCost];
    const target = newData.filter(item => key === item.id)[0];
    if (target) {
      target[column] = value;
      this.setState({ applyOtherCost: newData });
    }
  };

  handleChangeRetail(value, key, column) {
    const newData = [...this.state.applyOtherCost];
    const target = newData.filter(item => key === item.id)[0];
    if (target) {
      target[column] = value;
      this.setState({ applyOtherCost: newData });
    }
  }

  editRetail(key) {
    const newData = [...this.state.applyOtherCost];
    const target = newData.filter(item => key === item.id)[0];
    if (target) {
      target.editable = true;
      target.isPreset = true;
      this.setState({ applyOtherCost: newData });
    }
  }

  saveRetail(key) {
    this.cacheDataRetail = this.state.applyOtherCost.map(item => ({ ...item }));
    const newData = [...this.state.applyOtherCost];
    const target = newData.filter(item => key === item.id)[0];
    if (target) {
      delete target.editable;
      target.isPreset = false;
      this.setState({ applyOtherCost: newData });
      this.cacheDataRetail = newData.map(item => ({ ...item }));
    }
  }
  cancelRetail(key) {
    this.cacheDataRetail = this.state.applyOtherCost.map(item => ({ ...item }));
    const newData = [...this.state.applyOtherCost];
    const target = newData.filter(item => key === item.id)[0];
    if (target) {
      Object.assign(target, this.cacheDataRetail.filter(item => key === item.id)[0]);
      delete target.editable;
      target.isPreset = false;
      this.setState({ applyOtherCost: newData });
    }
  }

  deleteRetail(key) {
    const newData = [...this.state.applyOtherCost];
    this.setState({ applyOtherCost: newData.filter(item => item.key !== id) });
  }

  handleOtherCost = () => {
    const newApplyOtherCost = [...this.state.applyOtherCost];
    const newRecode = {
      id: newApplyOtherCost.length + 1,
      key: newApplyOtherCost.length + 1,
      cost: '',
      projectId: this.state.projectId,
      editable: true,
      isNew: true,
      isPreset: true,
      costName: '',
      // <Select>
      /* //   <Option value={1}>上牌服务费</Option>
        //   <Option value={2}>GPS安装费</Option>
        //   <Option value={3}>保险服务费</Option>
        //   <Option value={4}>其他</Option> */
      // </Select>
    };
    newApplyOtherCost.push(newRecode);
    this.setState({ applyOtherCost: newApplyOtherCost });
  };

  handleBusinessSubmit = () => {
    const { dispatch } = this.props;
    let intrestFlag = true;
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // this.state.intrestList.map(item => {
        //   console.log('validateFieldsAndScroll', item);
        //   if (item.nper == values.loanDuration) {
        //     if (values.intrest > item.priceHigh || values.intrest < item.priceLow) {
        //       message.warning('不能大于或小于经销商的手续费率');
        //       intrestFlag = false;
        //       return;
        //     }
        //   }
        // });
        // if (intrestFlag) {
        // console.log("values", values)
        dispatch({
          type: 'apply/saveBusiness',
          payload: {
            id: this.state.projectId,
            ...values,
            addLoanAmt: this.state.addLoanAmt,
            otherCost: this.state.applyOtherCost,
          },
          callback: () => {
            const { apply: { applyResult } } = this.props;
            if (applyResult.code == 200) {
              message.success('提交成功');
              dispatch({
                type: 'apply/detailsApply',
                payload: {
                  projectId: this.state.projectId,
                },
              });
            } else {
              message.error(applyResult.message);
            }
          },
        });
        // }
      }
    });
  };

  renderOption = data => {
    const options = [];
    data.map(item => {
      options.push(
        <Option value={item.nper} key={item.nper}>
          {item.nper}
        </Option>
      );
    });
    return options;
  };

  handleRemoveFile = file => {
    const { dispatch } = this.props;
    const uid = file.url.split('/');
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: uid[4],
      },
      callback: () => {
        const { apply: { applyResult } } = this.props;
        if (applyResult.code == 200) {
          message.success('删除成功');
          dispatch({
            type: 'apply/detailsApply',
            payload: {
              projectId: this.state.projectId,
            },
          });
        } else {
          message.error(applyResult.message);
        }
      },
    });
  };
  //资产价格
  handleDealerName = e => {
    this.setState({ assetPrices: e.target.value });
  };
  //首付款
  handleFirstPayment = e => {
    this.setState({ firstPayment: e.target.value });
  };
  //贷款金额
  handleLoanAmt = value => {
    this.setState({ loanAmount: value });
  };

  //贷款周期
  handleLoanDuration = value => {
    sessionStorage.setItem('loanPeriod', value);
    this.setState({ loanPeriod: value });
  };
  //手续费
  handleIntrest = value => {
    this.setState({ poundage: value });
  };
  //手续费率
  handlePoundageProportion = value => {
    this.setState({ poundageProportion: value, feeInputFlag: true });
  };
  //附加消费分期金额
  handleAddLoanAmt = value => {
    if (value) {
      this.setState({
        addLoanAmt: value,
        feeInputFlag: true,
      });
    } else {
      this.setState({
        addLoanAmt: 0,
        feeInputFlag: true,
      });
    }
  };
  //申请金额
  handleAddAmt = value => {
    this.setState({ applyAmt: value });
  };

  render() {
    const { risk, isForFamilyMember } = this.props;
    const { customers } = risk;
    const {
      assetPrices,
      firstPayment,
      firstPaymentProportion,
      loanAmount,
      poundageProportion,
      poundage,
      loanPeriod,
      eachMonth,
      addLoanAmt,
      feeInputFlag,
    } = this.state;
    const { apply: { applyListDetails, applyLoading, saveBusinessLoading } } = this.props;
    const { business } = applyListDetails;
    const { getFieldDecorator, getFieldValue, validateFieldsAndScroll } = this.props.form;
    const { applyDisabled } = this.props;
    const agreementFileUploadProps = {
      name: 'file',
      action: solo.uploadImg,
      multiple: true,
      headers: {
        authorization: 'authorization-text',
      },
      data: {
        projectId: this.state.projectId, //业务ID
        customerId: this.state.id, //客户ID
        attachType: '2', //0：图片；1：视频; 2:文件
        attachKind: '1510', //附近种类
        type: '', //图片类型
      },
      onChange: info => {
        if (info.file.status === 'done') {
          const newFileList = [...this.state.agreementFileList];
          // const newTypeFileList = [...this.state.agreementTypeFileList];
          newFileList.push(solo.imgShow + info.file.response.body.key);
          // newTypeFileList.push(info.fileList);
          this.setState({
            agreementFileList: newFileList,
            agreementTypeFileList: info.fileList,
          });
          message.success(`${info.file.name} 文件上传成功`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 文件上传失败.`);
        }
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    return (
      <Form>
        {/* {JSON.stringify(business)} */}
        {business && (
          <div>
            <Card type="inner" title="贷款业务信息">
              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label="业务编号" {...formItemLayout}>
                    {getFieldDecorator('bizNum', {
                      initialValue: business.bizNum,
                    })(<Input disabled />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="产品种类" {...formItemLayout}>
                    {getFieldDecorator('assetType', {
                      initialValue: business.assetType,
                    })(<Input disabled />)}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="资产价格" {...formItemLayout}>
                    {getFieldDecorator('dealerPrice', {
                      initialValue: assetPrices,
                    })(<Input disabled onChange={this.handleDealerName} />)}
                  </FormItem>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label="首付款" {...formItemLayout}>
                    {getFieldDecorator('firstPayment', {
                      initialValue: firstPayment,
                    })(
                      <Input
                        onChange={this.handleFirstPayment}
                        disabled={this.state.applyDisabled}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="首付款比例" {...formItemLayout}>
                    {getFieldDecorator('firstPayment1', {
                      //首付款/资产价格=首付款比例
                      initialValue:
                        assetPrices &&
                        firstPayment &&
                        (Number(firstPayment) / Number(assetPrices) * 100).toFixed(2),
                    })(
                      <InputNumber
                        min={0}
                        max={100}
                        style={{ width: '100%' }}
                        readOnly={true}
                        formatter={value => `${value}%`}
                        disabled
                      />
                    )}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="贷款金额" {...formItemLayout}>
                    {getFieldDecorator('loanAmt', {
                      initialValue:
                        assetPrices &&
                        firstPayment && //资产价格-首付款=贷款金额
                        Number(assetPrices) - Number(firstPayment),
                    })(
                      <InputNumber
                        min={0}
                        style={{ width: '100%' }}
                        disabled
                        onChange={this.handleLoanAmt}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label="附加消费分期金额" {...formItemLayout}>
                    {getFieldDecorator('addLoanAmt1', {
                      initialValue: addLoanAmt,
                    })(
                      <InputNumber
                        min={0}
                        onChange={this.handleAddLoanAmt}
                        disabled={this.state.applyDisabled}
                        style={{ width: '100%' }}
                      />
                    )}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="申请金额" {...formItemLayout}>
                    {getFieldDecorator('applyAmt', {
                      //贷款金额+附加消费分期金额=申请金额
                      initialValue:
                        assetPrices &&
                        firstPayment &&
                        (Number(assetPrices) - Number(firstPayment) + Number(addLoanAmt)).toFixed(
                          2
                        ),
                    })(
                      <InputNumber
                        min={0}
                        style={{ width: '100%' }}
                        disabled
                        onChange={this.handleAddAmt}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label="贷款周期" {...formItemLayout}>
                    {getFieldDecorator('loanDuration', {
                      initialValue: business.loanDuration,
                    })(
                      <Select
                        style={{ width: '100%' }}
                        disabled={this.state.applyDisabled}
                        onChange={this.handleLoanDuration}
                      >
                        {business && this.renderOption(business.intrestList)}
                      </Select>
                    )}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="手续费率" {...formItemLayout}>
                    {getFieldDecorator('intrest', {
                      initialValue: poundageProportion,
                    })(
                      <InputNumber
                        style={{ width: '100%' }}
                        min={0}
                        max={100}
                        formatter={value => `${value}%`}
                        parser={value => value.replace('%', '')}
                        placeholder="请输入"
                        disabled={this.state.applyDisabled}
                        onChange={this.handlePoundageProportion}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="手续费" {...formItemLayout}>
                    {getFieldDecorator('fee', {
                      //申请金额*手续费率=手续费
                      initialValue: !feeInputFlag
                        ? poundage
                        : assetPrices &&
                          firstPayment &&
                          poundageProportion &&
                          (
                            (Number(assetPrices) - Number(firstPayment) + Number(addLoanAmt)) *
                            Number(poundageProportion) /
                            100
                          ).toFixed(2),
                    })(
                      <InputNumber
                        min={0}
                        style={{ width: '100%' }}
                        disabled={this.state.applyDisabled}
                        onChange={this.handleIntrest}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label="月供" {...formItemLayout}>
                    {getFieldDecorator('payMonth', {
                      //(申请金额+手续费)/贷款周期=月供
                      initialValue: !feeInputFlag
                        ? assetPrices &&
                          firstPayment &&
                          loanPeriod &&
                          poundage &&
                          (
                            (Number(assetPrices) -
                              Number(firstPayment) +
                              Number(addLoanAmt) +
                              poundage) /
                            Number(loanPeriod)
                          ).toFixed(2)
                        : assetPrices &&
                          firstPayment &&
                          loanPeriod &&
                          poundageProportion &&
                          (
                            (Number(assetPrices) -
                              Number(firstPayment) +
                              Number(addLoanAmt) +
                              (Number(assetPrices) - Number(firstPayment) + Number(addLoanAmt)) *
                                Number(poundageProportion) /
                                100) /
                            Number(loanPeriod)
                          ).toFixed(2),
                    })(<Input readOnly={true} disabled />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="卡号" {...formItemLayout}>
                    {getFieldDecorator('cardNum', {
                      initialValue: business.cardNum,
                    })(<Input disabled={this.state.applyDisabled} />)}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="开卡时间" {...formItemLayout}>
                    {getFieldDecorator('cardTime', {
                      initialValue: business.cardTime && Moment(business.cardTime),
                    })(
                      <DatePicker
                        style={{ width: '100%' }}
                        format={monthFormat}
                        disabled={this.state.applyDisabled}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            <Card
              title="其他收费"
              type="inner"
              style={{ marginTop: '16px' }}
              extra={
                !this.state.applyDisabled ? (
                  <Button
                    shape="circle"
                    icon="plus"
                    size="small"
                    style={{ marginLeft: '16px' }}
                    onClick={this.handleOtherCost}
                  />
                ) : null
              }
            >
              <Table
                pagination={false}
                rowKey="id"
                columns={this.appendFeeColumns}
                dataSource={this.state.applyOtherCost}
              />
            </Card>
            <Card type="inner" style={{ marginTop: '16px' }}>
              <FormItem label="放款账号" {...formItemLayoutOfHorizon}>
                {getFieldDecorator('releaseAccount', {
                  initialValue: business.releaseAccount,
                })(<Input disabled={this.state.applyDisabled} />)}
              </FormItem>
              <FormItem label="放款时间" {...formItemLayoutOfHorizon}>
                {getFieldDecorator('releaseTime', {
                  initialValue: business.releaseTime && Moment(business.releaseTime),
                })(
                  <DatePicker
                    style={{ width: '100%' }}
                    format={monthFormat}
                    disabled={this.state.applyDisabled}
                  />
                )}
              </FormItem>
            </Card>
            <Card title="附件管理" type="inner" style={{ marginTop: '16px' }}>
              <FormItem label="业务申请表" {...formItemLayoutOfHorizon}>
                <Upload
                  {...agreementFileUploadProps}
                  defaultFileList={this.state.attachmentMap.attachs}
                >
                  <Button icon="upload" disabled={this.state.applyDisabled}>
                    上传文件
                  </Button>
                  {/* <Button style={{ marginLeft: '16px' }}>下载模板</Button> */}
                </Upload>
              </FormItem>
            </Card>
            <FormItem
              wrapperCol={{
                xs: { span: 24, offset: 0 },
                sm: { span: 16, offset: 8 },
              }}
              label=""
            >
              {applyDisabled ? (
                ''
              ) : (
                <Button
                  type="primary"
                  style={{ marginTop: '30px' }}
                  onClick={this.handleBusinessSubmit}
                  loading={saveBusinessLoading}
                >
                  保存
                </Button>
              )}
            </FormItem>
          </div>
        )}
      </Form>
    );
  }
}
